<?php

namespace app\api\model;

use app\admin\model\service\Service;
use app\admin\model\Technician;
use think\Model;

class Order extends Model
{

    public function orderSn ()
    {
        do {
            $order = $this->generateOrderNumber();
            $find = Order::where([
                'order_sn' => $order
            ])->find();
        } while ($find);
        return $order;
    }

    private function generateOrderNumber ()
    {
        $order_id_main = date('YmdHis') . rand(10000000, 99999999);

        $order_id_len = strlen($order_id_main);

        $order_id_sum = 0;

        for ($i = 0; $i < $order_id_len; $i++) {

            $order_id_sum += (int)(substr($order_id_main, $i, 1));

        }

        $osn = $order_id_main . str_pad((100 - $order_id_sum % 100) % 100, 2, '0', STR_PAD_LEFT);
        return $osn;
    }


    #关联服务表
    public function service ()
    {
        return $this->belongsTo(Service::class, 'service_id', 'service_id');
    }

    public function technician ()
    {
        return $this->belongsTo(Technician::class, 'technician_id', 'technician_id');
    }

    public function getOrderStateTextAttr ($value, $data)
    {
        $status = [
            'ToBePaid'  => '待支付',
            'Paid'      => '已支付',
            'SetOut'    => '技师上门中',
            'Reach'     => '技师已到达',
            'Start'     => '服务中',
            'Completed' => '已完成',
            'Canceled'  => '已取消',
            'Received'  => '技师已接单',
            'tchEnd'  => '技师完成服务',

        ];
        return $status[$data['order_state']];
    }
}